package cn.ubeta.b2c.widget.banner;

/**
 * Created by denny on 16/8/18.
 */

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.facebook.drawee.view.SimpleDraweeView;
import cn.ubeta.b2c.R;
import cn.ubeta.b2c.bean.BannerInfo;

import java.util.List;

import static cn.ubeta.b2c.product.ProductListFragment.setResImage;

public class BannerAdapter extends InfinitePagerAdapter {

    private Context mContext;
    private List<BannerInfo> array;

    public BannerAdapter(Context context, List<BannerInfo> array) {
        this.mContext = context;
        this.array = array;
    }

    public void setData(List<BannerInfo> array) {
        this.array = array;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return array == null ? 0 : array.size();
    }

    @Override
    public View getView(final int position, View view, ViewGroup container) {
        ViewHolder holder;
        if (view != null) {
            holder = (ViewHolder) view.getTag();
        } else {
            view = LayoutInflater.from(container.getContext()).inflate(R.layout.item_banner, container, false);
            holder = new ViewHolder(view);
            view.setTag(holder);
        }
        refreshItem(holder, position);

        return view;
    }

    private static class ViewHolder {
        SimpleDraweeView image;

        public ViewHolder(View view) {
            image = (SimpleDraweeView) view.findViewById(R.id.banner_image);
            // TODO hardcode灰色背景
            image.setBackgroundResource(R.color.white);
        }
    }

    private void refreshItem(ViewHolder holder, final int position) {
        final BannerInfo bannerInfo = array.get(position);
        setResImage(holder.image, bannerInfo.getImgRes());
        holder.image.setOnClickListener(v -> {
            // TODO 处理跳转
            //ActionHelper.process(mActivity, activityInfo);
        });
    }

    @Override
    public void notifyDataSetChanged() {
        int len = views.size() > getItemCount() ? getItemCount() : views.size();
        for (int i = 0; i < len; i++) {
            View itemView = views.get(i);
            if (itemView != null) {
                ViewHolder holder = (ViewHolder) itemView.getTag();
                if (holder != null)
                    refreshItem(holder, i);
            }
        }
        super.notifyDataSetChanged();
    }
}
